package org.dromara.web.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tencentyun.TLSSigAPIv2;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.web.properties.TrtcProperties;
import org.dromara.web.service.TencentImService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 腾讯IM服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TencentImServiceImpl implements TencentImService {

    private final TrtcProperties trtcProperties;

    @Override
    public boolean addFriend(String fromAccount, String toAccount, String remark, String groupName, String addWording) {
        try {
            Long sdkAppId = trtcProperties.getSdkAppId();
            TLSSigAPIv2 api = new TLSSigAPIv2(sdkAppId, trtcProperties.getSdkAppKey());
            String userSig = api.genUserSig(fromAccount, 180*86400);
            // 构建请求URL
            String url = String.format("%s?sdkappid=%d&identifier=%s&usersig=%s&random=%d&contenttype=json",
                trtcProperties.getImApiAddUrl(),
                trtcProperties.getSdkAppId(),
                trtcProperties.getIdentifier(),
                userSig,
                RandomUtil.randomLong(0, 4294967295L));

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("From_Account", fromAccount);

            List<Map<String, String>> addFriendItems = new ArrayList<>();
            Map<String, String> addFriendItem = new HashMap<>();
            addFriendItem.put("To_Account", toAccount);
            addFriendItem.put("Remark", remark);
            addFriendItem.put("GroupName", groupName);
            addFriendItem.put("AddSource", "AddSource_Type_Web");
            addFriendItem.put("AddWording", addWording);
            addFriendItems.add(addFriendItem);
            requestBody.put("AddFriendItem", addFriendItems);

            requestBody.put("AddType", "Add_Type_Both");
            requestBody.put("ForceAddFlags", 1);

            // 发送请求
            String response = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(requestBody))
                .execute()
                .body();

            // 解析响应
            JSONObject jsonResponse = JSONUtil.parseObj(response);
            String actionStatus = jsonResponse.getStr("ActionStatus");
            String errorInfo = jsonResponse.getStr("ErrorInfo");
            Integer errorCode = jsonResponse.getInt("ErrorCode");

            if ("OK".equals(actionStatus) && errorCode == 0) {
                log.info("添加好友成功: fromAccount={}, toAccount={}", fromAccount, toAccount);
                return true;
            } else {
                log.error("添加好友失败: fromAccount={}, toAccount={}, errorCode={}, errorInfo={}",
                    fromAccount, toAccount, errorCode, errorInfo);
                return false;
            }
        } catch (Exception e) {
            log.error("添加好友异常: fromAccount={}, toAccount={}", fromAccount, toAccount, e);
            return false;
        }
    }

    @Override
    public boolean importAccount(String userId, String nick, String faceUrl) {
        try {
            Long sdkAppId = trtcProperties.getSdkAppId();
            TLSSigAPIv2 api = new TLSSigAPIv2(sdkAppId, trtcProperties.getSdkAppKey());
            String userSig = api.genUserSig(trtcProperties.getIdentifier(), 180*86400);
            
            // 构建请求URL
            String url = String.format("https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=%d&identifier=%s&usersig=%s&random=%d&contenttype=json",
                sdkAppId,
                trtcProperties.getIdentifier(),
                userSig,
                RandomUtil.randomLong(0, 4294967295L));

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("UserID", userId);
            requestBody.put("Nick", nick);
            requestBody.put("FaceUrl", faceUrl);

            // 发送请求
            String response = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(requestBody))
                .execute()
                .body();

            // 解析响应
            JSONObject jsonResponse = JSONUtil.parseObj(response);
            String actionStatus = jsonResponse.getStr("ActionStatus");
            String errorInfo = jsonResponse.getStr("ErrorInfo");
            Integer errorCode = jsonResponse.getInt("ErrorCode");

            if ("OK".equals(actionStatus) && errorCode == 0) {
                log.info("导入用户账号成功: userId={}, nick={}", userId, nick);
                return true;
            } else {
                log.error("导入用户账号失败: userId={}, nick={}, errorCode={}, errorInfo={}",
                    userId, nick, errorCode, errorInfo);
                return false;
            }
        } catch (Exception e) {
            log.error("导入用户账号异常: userId={}, nick={}", userId, nick, e);
            return false;
        }
    }
}
